package com.coco.thread.syn;

/**
 * 类锁
 * 锁的是 同一个类的 同一个方法
 */
public class SynClass {

    private static Object obj = new Object();
    private static int count = 0;

    static class MyThread1 extends Thread{
        @Override
        public void run() {
            for(int i=0;i<1000;i++){
                SynClass.count1();
            }
            System.out.println(Thread.currentThread().getName()+ "--- " +count);
        }
    }


    static class MyThread2 extends Thread{
        @Override
        public void run() {
            for(int i=0;i<1000;i++){
                SynClass.count1();
            }
            System.out.println(Thread.currentThread().getName()+ "--- " +count);
        }
    }

//方式一
//    public synchronized static void count1(){
//        count++;
//    }

//    方式二
    public static void count1(){
        synchronized (obj){
            count++;
        }
    }

    public static void main(String[] args) throws InterruptedException {

        for(int i=0;i<5;i++){
           new MyThread1().start();
        }
        for(int i=0;i<2;i++){
            new MyThread2().start();
        }

        Thread.sleep(2000);
        System.out.println(count);
    }

}
